﻿using SmartRFIDSystem19.dao;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SmartRFIDSystem19.model;
using System.IO.Ports;
using System.Threading;

namespace SmartRFIDSystem19.view
{
    public partial class UserMain : Form
    {
        string idcard;
        public UserMain()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            InitializeComponent();
            serialPort2 = new SerialPort();
            serialPort2.DataReceived += serialPort1_DataReceived;

            try
            {


                string[] ports = SerialPort.GetPortNames();
                comPort.Items.AddRange(ports);
                //serialPort2.PortName = prots[0];
                serialPort2.BaudRate = 115200;//选择波特率
                serialPort2.DataBits = 8;//选择数据位
                serialPort2.StopBits = StopBits.One;
                serialPort2.Parity = Parity.None;

                // MessageBox.Show("串口已经打开！");
            }
            catch
            {

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (card_label.Text.Equals(""))
            {
                MessageBox.Show("请先读取卡号！");
                return;
            }
            LogDao.ExportBill(name_label.Text, card_label.Text);
        }

        private void LookBill_btn_Click(object sender, EventArgs e)
        {

        }

        private void Consume_btn_Click(object sender, EventArgs e)
        {
            string key = "FF FF FF FF FF FF";
            //获取消费金额
            float amount = float.Parse(amount_txt.Text);
            //获取消费备注
            string remark = remark_txt.Text;
            //获取卡号
            string mfid = card_label.Text;

            float m = LogDao.GetBalance(mfid) - amount;
            if (m < 0)
            {
                MessageBox.Show("余额不足！");
            }
            else
            {
                //调用消费方法完成消费-数据库
                LogDao.Consume(mfid, amount, remark);
                AccountDao.updateBalanceByCardId(mfid, m);
                //刷新显示
                UInt32 money = ((UInt32)(m) * 100);//使用Uint32是因为这是钱
                Byte[] s = PortUtils.add(money, key);
                serialPort2.Write(s, 0, 31);
                balance_label.Text = LogDao.GetBalance(mfid).ToString();
                //在富文本框中追加消费人姓名、卡号、消费金额、时间、余额、备注
                richTextBox1.AppendText("姓名：" + name_label.Text + "(" + mfid + ")" + "\t" + "消费金额：" + amount + "\n" + "时间：" + DateTime.Now.ToString() + "\t" + "余额：" + LogDao.GetBalance(mfid) + "\n" + "备注：" + remark + "\n");
                richTextBox1.AppendText("----------------------------------------------------------\n");
            }

        }

        private void UserMain_Load(object sender, EventArgs e)
        {
            this.StartPosition = FormStartPosition.CenterScreen;

            //init();


            //读取卡号

            //   MessageBox.Show(card_label.Text);//当这条语句存在 注释掉这条语句

            //这里的card_label.Text的值没更新过来
            //Thread.Sleep(200);

            // idcard = card_label.Text;

            ////通过卡号查询姓名
            //string name = AccountDao.getNameByCardId(idcard);
            ////通过卡号查询余额
            //float balance = AccountDao.getBalanceByCardId(idcard);
            ////显示卡号
            //card_label.Text = idcard;
            ////显示姓名
            //name_label.Text = name;
            ////显示余额
            //balance_label.Text = balance.ToString();
            // if (!card_label.Text.Equals(""))
            //   {
            //idcard = "bcd";//调试
            //  name_label.Text = AccountDao.getNameByCardId(idcard);
            //  balance_label.Text = AccountDao.getBalanceByCardId(idcard).ToString();
            // }
        }

        private void Recharge_btn_Click(object sender, EventArgs e)
        {
            string key = "FF FF FF FF FF FF";
            //获取充值金额
            float amount = float.Parse(amount_txt.Text);
            //获取充值备注
            string remark = remark_txt.Text;
            //获取卡号
            string mfid = card_label.Text;
            //调用充值方法完成充值-数据库
            float m = LogDao.GetBalance(mfid) + amount;
            LogDao.Recharge(mfid, amount, remark);
            AccountDao.updateBalanceByCardId(mfid, m);
            UInt32 money = (UInt32)((m) * 100);//使用Uint32是因为这是钱
            Byte[] s = PortUtils.add(money, key);
            serialPort2.Write(s, 0, 31);
            //刷新显示
            balance_label.Text = LogDao.GetBalance(mfid).ToString();
            //在富文本框中追加消费人姓名、卡号、充值金额、时间、余额、备注
            richTextBox1.AppendText("姓名：" + name_label.Text + "(" + mfid + ")" + "\t" + "充值金额：" + amount + "\n" + "时间：" + DateTime.Now.ToString() + "\t" + "余额：" + LogDao.GetBalance(mfid) + "\n" + "备注：" + remark + "\n");
            richTextBox1.AppendText("----------------------------------------------------------\n");

        }
        public static int flag = 1;
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(200);//每次指令的时间间隔为200ms
                int length = serialPort2.BytesToRead;
                Byte[] buff = new Byte[100];//定义接收数据的数组
                serialPort2.Read(buff, 0, length);//接收数据
                int idx, ecc_rcv = 0;//idx 数组下标  ecc_rcv校验位
                string strReceive = "";//定义接收到的卡号
                string strSourse = "";//定义接收到的数据
                string moneytext = "";//定义读出来的钱
                for (idx = 2; idx < length - 1; idx++)//计算校验
                {
                    ecc_rcv ^= buff[idx];
                }
                int money = 0;//定义读出来的钱
                if (length <= 0) return;//如果接收到的字节出问题直接返回
                if (Convert.ToByte(ecc_rcv) == buff[length - 1] && (buff[0] == 0xCD && buff[1] == 0xDC))
                {

                    if (buff[3] == 0x81)//表示接收成功
                    {
                        if (buff[4] == 0x04)//接收卡号的指令
                        {
                            for (idx = 5; idx < length - 1; idx++)//把卡号转化为字符串
                            {
                                strReceive += Convert.ToString(buff[idx], 16).PadLeft(2, '0');
                            }

                            Invoke(new Action(() =>//显示卡号文本
                            {
                                card_label.Text = (strReceive.ToUpper().Trim());

                                // txBmcardsn.AppendText(strReceive.ToUpper().Trim() + '\n');
                            }));
                        }
                        else if (buff[4] == 0x12)
                        {//读数据块
                            if (flag == 1)
                            {//把读写数据块返回的指令转化为字符串
                                for (idx = 0; idx < length; idx++)
                                {

                                    strSourse += Convert.ToString(buff[idx], 16).PadLeft(2, '0') + " ";
                                }
                                Invoke((new Action(() =>
                                {
                                    //  textBox1.AppendText(strSourse.ToUpper().Trim() + "\r\n");

                                })));
                            }
                            if (flag == 0)
                            {
                                for (idx = 19; idx <= 22; idx++)
                                {
                                    moneytext += Convert.ToString(buff[idx], 16).PadLeft(2, '0');
                                }
                                money = Convert.ToInt32(moneytext, 16);
                                Invoke((new Action(() =>
                                {
                                    balance_label.Text = money * 1.0 / 100 + "";
                                })));
                            }
                        }
                        else if (buff[4] == 0x00)//接收指令成功
                        {
                            for (idx = 0; idx < length; idx++)
                            {
                                strSourse += Convert.ToString(buff[idx], 16).PadLeft(2, '0') + " ";
                            }

                            Invoke((new Action(() =>
                            {
                                // textBox1.AppendText(strSourse.ToUpper().Trim() + "\r\n");
                            })));

                        }


                    }

                }
            }
            catch (Exception err)
            {
                //MessageBox.Show(err.ToString());
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void card_label_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            if (!serialPort2.IsOpen)
            {
                serialPort2.PortName = comPort.Text;
                serialPort2.Open();//打开串口
            }
            card_label.Text = "";
            try
            {
                Byte[] s = PortUtils.getCardId();
                serialPort2.Write(s, 0, 6);
                MessageBox.Show("正在读卡");
                //线程睡眠200ms
                //Thread.Sleep(200);

            }
            catch
            {
                MessageBox.Show("串口未打开");
            }
            idcard = card_label.Text;
            //通过卡号查询姓名
            string name = AccountDao.getNameByCardId(idcard);
            // MessageBox.Show(name);
            //通过卡号查询余额
            float balance = AccountDao.getBalanceByCardId(idcard);
            //显示卡号
            // card_label.Text = idcard;
            //显示姓名
            name_label.Text = name;
            //显示余额
            balance_label.Text = balance.ToString();
            if (name_label.Text != "")
            {
                MessageBox.Show("读卡成功");
            }
            else
            {
                MessageBox.Show("获取信息失败，请检查卡片是否放置正确或卡片是否初始化");
            }
        }




        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void clear_btn_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }



        private void button2_Click(object sender, EventArgs e)
        {
            if (serialPort2.IsOpen)
            {
                serialPort2.Close();//关闭串口
                MessageBox.Show("串口已经关闭！");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {

        }

        private void comPort_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
